<template>
  <div class="auto-style">
    <el-dialog v-model="show" title="一键排版" width="650px" @close="closeDialog">
      <div v-if="!hasDesigned" v-loading="designLoading">
        <h3 class="choose-title">请选择排版格式</h3>
        <div class="format-list">
          <div class="format-box" v-for="item in formatList" :key="item.id" @mouseenter="showMask(item)" @mouseleave="hideMask(item)">
            <div class="format-item">
              <div class="format-item-name">{{item.name}}</div>
              <div class="format-item-description">{{item.description}}</div>
              <div class="format-item-default" v-show="item.isDefault">默</div>
            </div>
            <div class="format-box-mask" v-show="item.showMask">
              <el-button type="primary" size="small" @click="handleFormat(item.id)">使用排版</el-button>
              <!-- <el-button v-show="!item.isDefault" size="small" style="margin: 4px 0 0;" @click="handleSetDefault(item)">设为默认</el-button> -->
              <div class="format-box-mask-default" v-show="!item.isDefault" @click="handleSetDefault(item)">默</div>
              <div class="format-box-mask-btn">
                <el-button-group>
                  <el-button size="small" :icon="Delete" @click="handleDelete(item.id)" />
                  <el-button size="small" :icon="Edit" @click="handleEdit(item)" />
                </el-button-group>
              </div>
            </div>
          </div>
          <div class="format-add">
            <div class="format-item" @click="showFormatSetting = true">
              <el-icon :size="24"><Plus /></el-icon>
            </div>
          </div>
          <div v-for="n in 3 - (formatList.length % 4)" :key="n" style="width: calc((100% - 30px) / 4);height: 0;"></div>
        </div>
      </div>
      <div v-else>
        <el-result icon="success" title="排版成功" sub-title="">
          <template #sub-title>
            <el-button type="primary" link @click="handleChange">不满意，切换格式</el-button>
          </template>
          <template #extra>
            <el-button @click="handlePreview">预览结果</el-button>
            <el-button type="primary" @click="handleResult">使用结果</el-button>
          </template>
        </el-result>
      </div>
    </el-dialog>
    <!-- 格式设置 -->
    <el-dialog v-model="showFormatSetting" :title="formatForm.id ? '修改格式' : '添加格式'" width="600px" align-center @close="closeFormatSetting">
        <el-form ref="formatFormRef" :model="formatForm" :rules="formatFormRules" label-position="right" label-width="100px"> 
          <el-form-item label="格式名称" prop="name">
            <el-input v-model="formatForm.name" placeholder="请输入格式名称" />
          </el-form-item>
          <el-form-item label="设为默认">
            <el-radio-group v-model="formatForm.isDefault">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false" style="margin-left: 10px;">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="格式描述">
            <el-input v-model="formatForm.description" type="textarea" :rows="3" placeholder="请输入格式描述" />
          </el-form-item>
          <el-form-item label="格式规则" prop="rule">
            <div style="width: 100%; height: 500px;">
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showFormatSetting = false">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
          </span>
        </template>
    </el-dialog>
    <!-- 结果预览 -->
    <el-dialog v-model="showPreview" width="1400px" title="排版结果预览" class="content-compare-dialog" :close-on-press-escape="false" :close-on-click-modal="false">
      <div class="content-compare">
        <div class="old-content" v-html="originContent"></div>
        <div class="new-content" v-html="newContent"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable */
import { ref, computed, reactive } from 'vue'
import { Plus, Delete, Edit } from '@element-plus/icons-vue'
import { addFormat, updateFormat, deleteFormat } from "@/api/layout-template"
import { useStore } from 'vuex'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  instance: {
    type: Object,
    default: () => {}
  },
  fieldsValue: {
    type: Object,
    default: () => {}
  },
  formatList: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(['update:show', 'updateList'])
const store = useStore()
const groupId = ref(store.getters.userInfo.groupId)
const editor = computed(() => props.instance)
const fieldsValue = computed(() => props.fieldsValue)
const show = computed({
  get() {
    return props.show
  },
  set(value) {
    emits('update:show', value)
  }
})

const formatList = computed(() => props.formatList)
// 显示遮罩
const showMask = (item) => {
  item.showMask = true
}
// 隐藏遮罩
const hideMask = (item) => {
  item.showMask = false
}
// 使用排版
const originContent = ref('')
const newContent = ref('')
const designLoading = ref(false)
const hasDesigned = ref(false)
const handleFormat = (id) => {
  designLoading.value = true
  originContent.value = editor.value.activeEditor.getContent()
  const format = formatList.value.find(item => item.id === id)
  editor.value.activeEditor.plugins.layout.doAction(format.rule)
  newContent.value = editor.value.activeEditor.getContent()
  setTimeout(() => {
    hasDesigned.value = true
    designLoading.value = false
  }, 800)
  // 撤销操作
  editor.value.activeEditor.undoManager.undo()
}
// 设为默认
const handleSetDefault = async (format) => {
  const data = {
    id: format.id,
    isDefault: true
  }
  const res = await updateFormat(data)
  if(res.code === 20000){
    emits('updateList')
  }
}
// 添加格式
const showFormatSetting = ref(false)
const formatFormRef = ref(null)
const validateRule = (rule, value, callback) => {
  if (!ruleJson.value) {
    callback(new Error('格式规则不能为空'))
  } else {
    callback()
  }
}
const formatFormRules = reactive({
  name: [
    { required: true, message: '格式名称不能为空', trigger: 'blur' }
  ],
  rule: [
    { required: true, validator: validateRule, trigger: 'blur' }
  ]
})
const defaultFormatForm = reactive({
  name: '',
  groupId: groupId.value,
  isDefault: false,
  description: '',
  rule: ''
})
const formatForm = ref(Object.assign({}, defaultFormatForm))
const handleUpdateFormat = (data) => {
  formatForm.value = Object.assign({}, data)
}
const handleConfirm = () => {
  formatFormRef.value.validate(async (valid) => {
    if (valid) {
      formatForm.value.rule = ruleJson.value.replace(/\r\n|\n|\r|\t/gm, '')
      if (formatForm.value.id) {
        await updateFormat(formatForm.value)
      } else {
        await addFormat(formatForm.value)
      }
      showFormatSetting.value = false
      emits('updateList')
    }
  })
}
// 编辑格式
const ruleJson = ref('')
const handleEdit = (data) => {
  formatForm.value = Object.assign({}, data)
  ruleJson.value = JSON.stringify(formatForm.value.rule, null, 2)
  showFormatSetting.value = true
}
// 删除格式
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    deleteFormat({id}).then(res => {
      if(res.code === 20000){
        emits('updateList')
      }
    })
  }).catch(() => {})
}
// 关闭弹窗
const closeFormatSetting = () => {
  formatFormRef.value.resetFields()
  formatForm.value = Object.assign({}, defaultFormatForm)
}
// 切换模板
const handleChange = () => {
  hasDesigned.value = false
  newContent.value = ''
  originContent.value = ''
  ruleJson.value = ''
}
// 预览结果
const showPreview = ref(false)
const handlePreview = () => {
  showPreview.value = true
}
// 使用结果
const handleResult = () => {
  emits('update:show', false)
  editor.value.activeEditor.plugins.layout.doAction()
  fieldsValue.value[tinymce.activeEditor.id].replace(/layoutFV/g, "")
  editor.value.activeEditor.dom.$(".layoutFV").removeClass("layoutFV")
}
// 关闭弹窗恢复默认
const closeDialog = () => {
  hasDesigned.value = false
  newContent.value = ''
  originContent.value = ''
  ruleJson.value = ''
}
</script>

<style lang='scss' scoped>
.auto-style{
  .custom-setting{
    padding: 20px;
    background: #e4e4e4;
  }
  .choose-title{
    margin-bottom: 20px;
    width: 100%;
    text-align: center;
  }
  .format-list{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .format-add,
    .format-box{
      position: relative;
      margin-bottom: 15px;
      width: calc((100% - 30px) / 4);
      border: 1px solid #e4e6eb;
      border-radius: 4px;
      overflow: hidden;
      .format-item{
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 10px;
        margin: 2px;
        height: 91px;
        box-sizing: border-box;
        background: #f5f7f9;
        .format-item-name{
          margin-bottom: 20px;
          font-size: 14px;
          font-weight: bold;
        }
        .format-item-description{
          font-size: 12px;
          color: #aaa;
          text-align: center;
        }
        .format-item-default{
          position: absolute;
          top: 0;
          right: 0;
          width: 20px;
          height: 20px;
          border-end-start-radius: 100%;
          font-size: 12px;
          text-align: center;
          color: #fff;
          background: $mainColor;
        }
      }
      .format-box-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        transition: opacity 0.3s ease;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .format-box-mask-btn{
          margin-top: 5px;
        }
        .format-box-mask-default{
          position: absolute;
          top: 2px;
          right: 2px;
          width: 20px;
          height: 20px;
          border-end-start-radius: 100%;
          font-size: 12px;
          text-align: center;
          color: #fff;
          background: #909399;
          cursor: pointer;
        }
      }
    }
    .format-add{
      cursor: pointer;
      .format-item{
        justify-content: center;
      }
    }
    .format-box:hover{
      border-color: $mainColor;
      .format-item{
        opacity: 0.3;
      }
    }
  }
}
.content-compare-dialog{
  .content-compare{
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    .old-content,
    .new-content
    {
      position: relative;
      width: 50%;
      padding: 0 30px;
      padding-top: 20px;
      overflow-x: auto;
      &::after{
        content:'当前排版';
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        color: #aaa;
      }
    }
    .new-content{
    }
    .old-content{
      &::after{
        content:'原始排版';
      }
    }
    .old-content{
      &::before{
        content:'';
        position: absolute;
        top: 0;
        right: 0;
        width: 1px;
        height: 100%;
        background-color: rgba(139, 143, 145, 0.3);
        margin: 0 3px;
        z-index: 1;
      }
    }
  }
}
</style>